/**
 * Created by thomas on 2017/5/2.
 */
import React,{Component} from 'react';
import ajax from "./ajax";
import limit_scroll from "./limit_scroll";
import { withRouter } from 'react-router-dom'
let circle_c=1;
let time_x=undefined;
class Record extends React.Component{
    constructor(props) {
        super(props);
        this.state= {
            select_m:false,
            sign_header_ani:false,
            times:["2017.05.06","2017.05.07","2017.05.08"],
            now_times_index:1,
            now_time_s:"",
            show_num:1,
            now_time:"",
            static_time:"",
            header_w:(document.body.clientWidth*0.65),
            nav:[true,false,false],
            click_t:false,
            click_b:false,
            click_m:false,
            limit_time:"",
            ajax_mess:JSON.parse(sessionStorage.getItem("record_mess")),
            pre:"",
            sex_r:"",
            hid_load:true,
            mask:false,
            flag_fat:false,
            style_2:document.getElementById("style_2"),
            date_cn:"今天",

        };
        this.add_c = this.add_c.bind(this);
        this.main_click = this.main_click.bind(this);
        this.cricle=this.cricle.bind(this);
        this.add_c=this.add_c.bind(this);
        this.qm_show=this.qm_show.bind(this);
        this.step=this.step.bind(this);
    }
     change_time_stamp(date1,n){
         let date = new Date(date1*1000);//获取当前时间
         let day = date.getDate()+n;
         let ThreeDayAgo = date.setDate(day);//设置天数 -1 天
         return ThreeDayAgo/1000
     }

     //头顶的日期
     change_date(){
         if(this.state.now_time_s == this.state.static_time){
             this.setState({
                 date_cn:'今天'
             })
             style_2.innerHTML += `#arrow_r:before {
                                               border-left-color: #fbeded;
                                               right: 20px;
                                    }`
         }else{
             this.setState({
                 date_cn:" "
             })
             style_2.innerHTML =""
         }
     }
    change_time(e){
        try{
            cancelAnimationFrame(time_x);
        }catch (e){
        }
        time_x=undefined;
        this.setState({
            click_t:false,
            click_b:false,
            click_m:false
        });
        circle_c=1;
        let dom = this.refs.record_header_inner_box;
        let sex= this.state.sex_r;
        //e 是判断 左右的
        // 后面的判断是 用来 做 限制的
        //不能 大过当前时间（今天） 你的今天啊! :)
        if(e < 0 && this.state.static_time > this.state.now_time_s){
            let t=this.change_time_stamp(this.state.now_time_s,1);
            this.setState({
                now_time_s:t,
                now_time : this.format(t),
                sign_header_ani : true
            },() =>{
               ajax({
                   meth:"post",
                   url:"http://woxiaoshitang.com/activity/health.php/Index/ajaxtime",
                   data:"sex="+sex+"&openid="+sessionStorage.getItem("op_id")+"&time="+t,
                   cb:(e) =>{

                       this.refs.record_main.scrollTop=0;
                       this.setState({
                           flag_fat:false
                       });
                       let mess=JSON.parse(e);


                       circle_c=1;
                       this.setState({
                           ajax_mess:mess,
                           pre:JSON.parse(e).exercise / mess.quantity *100/2
                       });

                       this.change_date();
                       this.cricle();
                   }
               })
            })
        }else if(e > 0){//获取之前时间数据的 ！！QAQ
            let t=this.change_time_stamp(this.state.now_time_s,-1);
            this.setState({
                now_time_s:t,
                now_time : this.format(t),
                sign_header_ani : true
            },()=>{
                ajax({
                    meth:"post",
                    url:"http://woxiaoshitang.com/activity/health.php/Index/ajaxtime",
                    data:"sex="+sex+"&openid="+sessionStorage.getItem("op_id")+"&time="+t,
                    cb:(e) =>{
                        this.refs.record_main.scrollTop=0;
                        this.setState({
                            flag_fat:false
                        });
                        circle_c=1;
                        let mess=JSON.parse(e);
                        this.setState({
                            ajax_mess:mess,
                            pre:JSON.parse(e).exercise / mess.quantity *100/2
                        })

                        this.change_date();
                        this.cricle()
                    }
                })
            })
        }
        dom.addEventListener("webkitAnimationEnd", () => {
            this.setState({
                sign_header_ani: false
            })
        })
    }
    format(shijianchuo)
    {
        function add0(m){return m<10?'0'+m:m }
//shijianchuo是整数，否则要parseInt转换
        let time = new Date(shijianchuo*1000);
        let y = time.getFullYear();
        let m = time.getMonth()+1;
        let d = time.getDate();
        return y+'-'+add0(m)+'-'+add0(d)
    }
    nav_click(e,num){
        //先停止动画
        try{
            cancelAnimationFrame(time_x);
        }catch (e){
        }
        time_x=undefined;
        this.setState({
            click_t:false,
            click_b:false,
            click_m:false
        })
        let map=this.state.nav;
        //先全部 去掉
        map.forEach(function(item,index){
            if(index === e)
            {
                map[index] = true
            }
            else
            {map[index] = false}
        });
        this.setState({
            nav:map
        },()=>{
            let sex= this.state.sex_r;
            ajax({
                meth:"post",
                url:"http://woxiaoshitang.com/activity/health.php/Index/ajaxtime",
                data:"sex="+sex+"&openid="+sessionStorage.getItem("op_id")+"&time="+this.state.now_time_s+"&parameter="+num,
                cb:(e) =>{
                    this.refs.record_main.scrollTop=0;
                    circle_c=1;
                    let mess=JSON.parse(e);
                    this.setState({
                        ajax_mess:mess,
                        pre:JSON.parse(e).exercise / mess.quantity *100/2
                    });
                  //this.cricle()
                }
            })
        })
    }

    main_click(e){
        sessionStorage.setItem("now_time_s",this.state.now_time_s);
        circle_c=1;
        let bf=this.state.ajax_mess.breakfast;
        let lun =this.state.ajax_mess.lunch;
        let supper =this.state.ajax_mess.supper;
        if(e == "click_t"){
            ajax({
                url:"http://woxiaoshitang.com/activity/health.php/Index/getwriteOffWeight?message=1",
                meth:"get",
                cb:(e)=>{
                        sessionStorage.setItem("push_img_mess",e);
                        sessionStorage.setItem("sel_record","breakfast");
                        sessionStorage.setItem("eng","breakfastenergy");
                        sessionStorage.setItem("now_time",this.state.now_time_s);
                        sessionStorage.setItem("mess_push",1);
                        this.props.history.push('/push_img')
                }
            })
            return
        }else if(e == "click_m"){
            ajax({
                url:"http://woxiaoshitang.com/activity/health.php/Index/getwriteOffWeight?message=2",
                meth:"get",
                cb:(e)=>{
                    sessionStorage.setItem("push_img_mess",e);
                    sessionStorage.setItem("sel_record","lunch");
                    sessionStorage.setItem("eng","lunchenergy");
                    sessionStorage.setItem("now_time",this.state.now_time_s);
                    sessionStorage.setItem("mess_push",2);
                    this.props.history.push('/push_img');
                }
            })
            return
        }else if(e == "click_b"){
            ajax({
                url:"http://woxiaoshitang.com/activity/health.php/Index/getwriteOffWeight?message=3",
                meth:"get",
                cb:(e)=>{
                    sessionStorage.setItem("push_img_mess",e);
                    sessionStorage.setItem("sel_record","supper");
                    sessionStorage.setItem("eng","supperenergy");
                    sessionStorage.setItem("now_time",this.state.now_time_s);
                    sessionStorage.setItem("mess_push",3);
                    this.props.history.push('/push_img');
                }
            })
            return
        }
        this.setState({
          [e]:!this.state[e]
        })
    }

    add_c(){
        if(this.state.pre>100/2){
            this.setState({
                pre:100/2,
                flag_fat:true
            });
        }
        // show_num+=18.25
        this.setState({
            show_num:(this.state.show_num+=18)
        },()=>{
            if(this.state.pre >=1){
                time_x = requestAnimationFrame(this.add_c);
                // console.log(this.state.ajax_mess.quantity)
                //if(this.state.show_num < this.state.ajax_mess.quantity){
                    circle_c+=1.98*2;
                    try{
                        this.refs.svg.style.strokeDasharray = circle_c+",340";
                    }catch (e){

                    }
                this.setState({
                    pre:this.state.pre-1
                });
               // }
            }else{
                this.setState({
                    show_num:this.state.ajax_mess.exercise,
                    // hid_load:true
                },()=>{
                    circle_c=1;
                })
            }
        })
    }

    step() {
       requestAnimationFrame(this.step);
    }

    cricle(){
        circle_c = 1;
        this.refs.svg.style.strokeDasharray= 1+",340";
       this.setState({
           // hid_load:false,
           show_num:0
       })
        time_x =requestAnimationFrame(this.add_c);
    }

    componentWillMount(){
        this.change_date();
        document.getElementsByTagName("title")[0].innerText="饮食记录";
        let sex = sessionStorage.getItem("sex") =="wm" ? sex=0:sex=1;
        // console.log(this.state.ajax_mess)
        let time = this.state.ajax_mess.time;
        this.format(new Date(time));
        let time_arr=[];
        this.setState({//显示的时间
            now_time :  this.format(this.state.ajax_mess.time)
        })
        //如果在push_img 回来 那个 time 是 这个页面 跳转时的时间
        //然而 static time 是不 可以改变的！！！！ （const 没用。。。gg（QAQ））
        if(sessionStorage.getItem("push_img_set_time") === 'true'){
            sessionStorage.setItem("push_img_set_time",false);
            this.setState({
                static_time:this.state.ajax_mess.static_time,
                now_time_s:this.state.ajax_mess.time,
                pre:this.state.ajax_mess.exercise  / this.state.ajax_mess.quantity *100/2,
                sex_r:sex
            })
        }else{
            this.setState({
                static_time:parseInt(this.state.ajax_mess.time),
                now_time_s:this.state.ajax_mess.time,
                pre:this.state.ajax_mess.exercise  / this.state.ajax_mess.quantity *100/2,
                sex_r:sex
            })
            sessionStorage.setItem("static_time",this.state.ajax_mess.time);
        }
        //初始化 点击图片改变
        // this.state.now_time = this.state.ajax_mess.time
    }

    componentDidMount(){
       let c_h= window.document.body.clientHeight;
       sessionStorage.setItem("c_h",c_h);
       this.refs.Record_contin.style.height=c_h+"px";
       this.refs.Record_contin.style.overflowX="hidden";
       this.refs.svg.style.strokeDasharray= 1+",340";
       this.cricle();
       // console.log( this.refs.Record_contin)
       limit_scroll(this.refs.record_main ,this.refs.Record_contin)
    }
    qm_show(){
        this.setState({
            mask:!this.state.mask
        })
    }

    for_food(name){
        let bf= this.state.ajax_mess[name];
        let x=[];
        if(bf == null){
          return;
        }
        for(let i = 0; i<bf.length; i++){
            x.push(
                <div className="nor_record_main_sub">
                    <div className="nor_record_main_sub_left">
                        {bf[i].content}
                    </div>
                    <div className="nor_record_main_sub_right">
                        {bf[i].energy}kcal
                    </div>
                </div>
            )
        }
        return x
    }
    flag_fat(){
             if(this.state.flag_fat){
                return(
                    <div className="record_main_bottom">
                       今天的热量已达标啦～别吃太多哦，不然会长胖。
                    </div>
                )
             }else{
                  return(
                      <div className="record_main_bottom">
                      已摄入热量{this.state.ajax_mess.exercise} kcal，还需 <span style={{color:'#e77a10'}}>{this.state.ajax_mess.quantity - this.state.ajax_mess.exercise}</span> kcal才达到健康水平
                      </div>
                  )
             }
     }
    render() {
        return (
            <div className="Record_contain" ref="Record_contin">
                <div className={this.state.mask?"qm_msak":"hid qm_msak"}>
                    <div className="qm_mask_main">
                        <div className="qm_mask_main_x" onClick={this.qm_show}>X</div>
                        <div className="qm_mask_main_top">
                            每天所需热量是由你的身高，体重，年龄和
                            运动量缩计算得出，为你一天的各种运动提
                            供能量。
                        </div>
                        <div className="qm_mask_main_bottom">
                            因个体体质状况不同，所需热量在1700~1
                            950千卡范围内都是合理的。
                        </div>
                    </div>
                </div>
                   <div className="record_header">
                       <div className="record_header_inner_l" onClick={() =>this.change_time(1)}>
                           <div id="arrow_l">&nbsp;</div>
                       </div>
                       <div className="record_header_inner_r" onClick={() =>this.change_time(-1)}>
                           <div id="arrow_r">&nbsp;</div>
                       </div>
                       {/*<div className="record_header_inner">*/}
                       <div className="record_header_inner_wrap" style={{width:this.state.header_w+"px"}}>
                           <div className={this.state.sign_header_ani?"record_header_inner_box record_header_ani":"record_header_inner_box"} ref="record_header_inner_box">
                               <span className="record_header_name">{this.state.date_cn}</span>
                               <span className="record_header_time">{this.state.now_time}</span>
                           </div>
                       </div>
                   </div>
                   <div className="Record_show_g">
                       <div className="contian_show_s">
                           <div className="qm" onClick={this.qm_show}>&nbsp;</div>
                           <img src="http://woxiaoshitang.com/activity/Public/img/health/circle_bg.png" className="circlr_bg"/>
                           <svg viewBox="0 0 100 100" style={{width:'55%',margin:'0 auto'}} className="svg_box">
                               <g fill="none" stroke-width="8" stroke-miterlimit="1" stroke-linecap="round" className="inner_posi">
                                   {/*<path className="strokeWidth" stroke="#FED74E" d="M50 95C25.1 95 5 74.9 5 50S25.1 5 50 5s45 20.1 45 45c0 24.8-20.3 65-65 65" style={{strokeDasharray:'100,260',strokeDashoffset:'10'}} ></path>*/}
                                   <path  ref="svg" className="strokeWidth" stroke="#fff" d="M50 95C25.1 95 5 74.9 5 50S25.1 5 50 5s45 20.1 45 45c0 24.8-20.3 45-45 45" style={{strokeDasharray: '33,340', strokeDashoffset: '-42'}}></path>
                                   {/*<!-- <path stroke="#FC9014" d="M50 85c-19.3 0-35-15.7-35-35s15.7-35 35-35 35 15.7 35 35-15.8 35-35 35" style="stroke-dasharray: 219.87; stroke-dashoffset: 143.134;"></path> -->*/}
                                   {/*<!-- <path stroke="#E22431" d="M50 75c-13.8 0-25-11.2-25-25s11.2-25 25-25 25 11.2 25 25-11.3 25-25 25" style="stroke-dasharray: 157.07; stroke-dashoffset: 102.252;"></path> -->*/}
                                   {/*<!-- <path stroke="#7A2A30" d="M50 65c-8.3 0-15-6.7-15-15s6.7-15 15-15 15 6.7 15 15c0 8.2-6.8 14.9-15 15" style="stroke-dasharray: 94.22; stroke-dashoffset: 61.3367;"></path> -->*/}
                               </g>
                           </svg>
                           <div className="svg_bot_l">
                               0kcal
                           </div>
                           <div className="svg_bot_r">
                               {this.state.ajax_mess.quantity}kcal
                           </div>
                           <div className="Record_num_mid">
                               {this.state.show_num}{/**/}<span className="Record_num_mid_unit">kcal</span>
                           </div>
                           <div className="Record_num_bot">
                               当前摄入的热量
                           </div>
                           {
                               this.flag_fat()
                           }
                       </div>
                   </div>
                   <div className="record_nav_mid">
                        <div className="record_nav_name">
                            今天运动量
                        </div>
                        <div className={this.state.nav[0]?"record_sel select_record_nav":"record_sel"} onClick={()=>this.nav_click(0,1.2)}>
                            轻度运动
                        </div>
                        <div className={this.state.nav[1]?"record_sel select_record_nav":"record_sel"} onClick={()=>this.nav_click(1,1.5)}>
                            中度运动
                        </div>
                        <div className={this.state.nav[2]?"record_sel select_record_nav":"record_sel"} onClick={()=>this.nav_click(2,1.8)}>
                            持续运动
                        </div>
                   </div>
                   <div className="record_main" ref="record_main">
                       {/*<div  className={this.state.hid_load?"cover_loading spe_record after_load_record":"cover_loading spe_record "} >*/}
                           {/*<div id="contain">*/}
                               {/*<div className="loading">*/}
                                   {/*<span></span>*/}
                                   {/*<span></span>*/}
                                   {/*<span></span>*/}
                                   {/*<span></span>*/}
                                   {/*<span></span>*/}
                               {/*</div>*/}
                           {/*</div>*/}
                       {/*</div>*/}
                       <div className="record_bf nor_record_main">
                            <div className="nor_record_main_top">
                                <div className="nor_record__left">
                                    <div className="record_top_icon">&nbsp;</div>
                                    <div className="nor_record_name">早餐</div>
                                </div>
                                 <div className={this.state.click_t?"noe_record_right":"noe_record_right"}
                                      onClick={(e)=> {
                                          e.stopPropagation();
                                          this.main_click('click_t')
                                      }
                                 }>&nbsp;</div>
                            </div>
                           <div className={this.state.click_t?"nor_record_main_sub_wrap":"nor_record_main_sub_wrap hidden"}>
                               {
                                   this.for_food("breakfast")
                               }
                           </div>
                       </div>
                       <div className="record_bf nor_record_main">
                           <div className="nor_record_main_top">
                               <div className="nor_record__left">
                                   <div className="record_mid_icon">&nbsp;</div>
                                   <div className="nor_record_name">午餐</div>
                               </div>
                               <div className={this.state.click_m?"noe_record_right":"noe_record_right"}  onClick={()=>this.main_click('click_m')}>&nbsp;</div>
                           </div>
                           <div className={this.state.click_m?"nor_record_main_sub_wrap":"nor_record_main_sub_wrap hidden"}>
                               {
                                this.for_food("lunch")
                               }
                           </div>
                       </div>
                       <div className="record_bf nor_record_main">
                       <div className="nor_record_main_top">
                           <div className="nor_record__left">
                               <div className="record_bot_icon">&nbsp;</div>
                               <div className="nor_record_name">晚餐</div>
                           </div>
                           <div className={this.state.click_b?"noe_record_right":"noe_record_right"}  onClick={()=>this.main_click('click_b')}>&nbsp;</div>
                       </div>
                         <div className={this.state.click_b?"nor_record_main_sub_wrap":"nor_record_main_sub_wrap hidden"}>
                           {
                               this.for_food("supper")
                           }
                           </div>
                       </div>
                   </div>
                   </div>
        );
    }
}
export default withRouter(Record);
